<template>
  <div class="pagination-wrapper">
    <el-pagination
        v-model:current-page="innerCurrentPage"
        v-model:page-size="innerPageSize"
        :page-sizes="pageSizes"
        :layout="layout"
        :total="total"
        :background="background"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
    />
  </div>
</template>

<script setup>
import { ref, watch } from 'vue'

const props = defineProps({
  currentPage: {
    type: Number,
    default: 1
  },
  pageSize: {
    type: Number,
    default: 10
  },
  total: {
    type: Number,
    required: true
  },
  pageSizes: {
    type: Array,
    default: () => [10, 15, 20, 25]
  },
  layout: {
    type: String,
    default: 'total, sizes, prev, pager, next, jumper'
  },
  background: {
    type: Boolean,
    default: true
  }
})

const emit = defineEmits(['update:currentPage', 'update:pageSize', 'page-change'])

const innerCurrentPage = ref(props.currentPage)
const innerPageSize = ref(props.pageSize)

// 同步外部props变化
watch(
    () => props.currentPage,
    (newVal) => {
      innerCurrentPage.value = newVal
    }
)

watch(
    () => props.pageSize,
    (newVal) => {
      innerPageSize.value = newVal
    }
)

const handleSizeChange = (newSize) => {
  innerPageSize.value = newSize
  emit('update:pageSize', newSize)
  emit('page-change', { page: innerCurrentPage.value, size: newSize })
}

const handleCurrentChange = (newPage) => {
  innerCurrentPage.value = newPage
  emit('update:currentPage', newPage)
  emit('page-change', { page: newPage, size: innerPageSize.value })
}
</script>

<style scoped>
.pagination-wrapper {
  margin-top: 20px;
  display: flex;
  justify-content: flex-end;
}
</style>